package com.esiag.pdsteam.ordonnancer;


import java.util.ArrayList;
import java.util.List;

import com.esiag.pdsteam.syncro.EPileType;
import com.esiag.pdsteam.syncro.IPileSynchro;
import com.esiag.pdsteam.syncro.PileTypeTuple;

public class Ordonnancer{
	private int mSequence;
	private List<EPileType> mPileTypes;
	private IPileSynchro mPileSynchro;
	
	public Ordonnancer(List<PileTypeTuple> pPileTypeTuples, IPileSynchro pPileSynchro) {
		mPileSynchro = pPileSynchro;
		mPileTypes = new ArrayList<EPileType>();
		for(final PileTypeTuple pileTypeTuple : pPileTypeTuples){
			if(pileTypeTuple.getSeconde() != 0){
				mPileTypes.add(pileTypeTuple.getEntity());
			}else{
				new Thread(new Runnable() {
					
					public void run() {
						while(true){
							try{
								Thread.sleep(pileTypeTuple.getSeconde());
								notifyToRead(pileTypeTuple.getEntity());
							}catch(Exception ex){
								ex.printStackTrace();
							}
						}
					}
				}).start();
			}
		}
		new Thread(new Runnable() {
			
			public void run() {
				while(true){
					notifyToRead();	
				}
			}
		}).start();
	}
	
	public void notifyToRead() {
		mSequence++;
		if(mSequence >= mPileTypes.size()){
			mSequence = 0;
		}
		notifyToRead(mPileTypes.get(mSequence));
	}
	
	synchronized private void notifyToRead(EPileType pPileType){
		mPileSynchro.write(pPileType);
	}
}
